
def f(row, col, n):
    # TODO 可以带上缓存
    if row==col and col==1:
        return 1

    r_c_sum = row + col     # 行列索引和

    if  r_c_sum <= n+1:
        # 上半部分三角形

        # 把行列之和相同的看做一组
        # (1,1)                    # 数值为1索引
        # (2,1, 1,2)               # 数值为2, 3索引
        # (3,1) (2,2) (1,3)        # 数值为4, 5, 6索引
        # (4,1) (3,2) (2,3) (1, 4) # 数值为7, 8, 9, 10

        # 如果要求某个索引的值, 等于这个索引的前一组数最后一位的值 + 它自己的列数
        # return f(1, r_c_sum-2, n) + col
        last_max_col = r_c_sum -2
        return last_max_col * (last_max_col + 1) // 2 + col
    else:
        # 下半部分通过上半部分对称的格子来计算
        return (n * n + 1) - f(n + 1 - row, n+1-col, n)

print( f(1, 1, 5))
print( f(2, 1, 5))
print( f(4, 3, 5))
print( f(5, 5, 5))

def gene_matric(n):
    line = (n + 1) * [None]
    # mat = [line for i in range(n+1)]      # 错误, 每行都引用相同数组
    mat = [list(line) for i in range(n+1)]      # 不得已而为之, 创建二维数组

    num = 0

    # get up
    for begin_row in range(1, n+1):
        for col in range(1, begin_row +1):
            num += 1

            assign_col = col
            assign_row = begin_row + 1 - col
            mat[assign_row][assign_col] = num
            # print("[%s][%s] ------> %s" % (assign_row, assign_col, mat[assign_row][assign_col]))

    # generate down by up: 对称性
    r_c_sum = n + 1         # row col 对称之和
    sum = n ** 2 + 1        # 对称之和
    for row in range(1, n+1):
        for col in range(1, n+1):
            if row + col <= n:
                mat[r_c_sum - row][r_c_sum - col] = sum - mat[row][col]
            if row + col > n:       # 对角线
                break
            # if row + col == n:
            #     break

    show(mat, n)

def show(mat, n):
    for row in range(1, n+1):
        for col in range(1, n+1):
            print(mat[row][col], sep="  ", end=" ")
        print()
